package com.software.cool.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.alibaba.fastjson.JSON;
import com.software.cool.api.admin.v1.vo.AdminLoginUserVO;
import com.software.cool.api.admin.v1.vo.AdminV1Result;
import com.software.cool.common.BaseMapper;
import com.software.cool.common.CommonContant;
import com.software.cool.entity.TbSysUser;
import com.software.cool.mapper.TbSysUserMapper;
import com.software.cool.service.ITbSysUserService;
import com.software.cool.utils.CommonUtils;
import com.software.cool.utils.DateUtils;
import com.software.cool.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.*;

@Service
@Slf4j
public class TbSysUserService extends BaseService<TbSysUser,String,Object> implements ITbSysUserService {

    @Resource
    private TbSysUserMapper mapper;
    @Override
    protected BaseMapper<TbSysUser> getBaseMapper() {
        return mapper;
    }
    @Value("${file.basedir}")
    private String basedir;
    @Resource
    private HttpServletRequest request;

    @Override
    public TbSysUser getLogin(String userName, String password){
        return mapper.getLogin(userName,password);
    }


    @Override
    public AdminV1Result edit(TbSysUser model) {
        AdminV1Result result=new AdminV1Result<>();
        Integer code=1;
        String msg="保存失败";
        try{
            if(model!=null){
                AdminLoginUserVO loginUser=this.getLoginUser(model.getToken());
                if(model.getUserType().equals("system")){model.setRoleId(1L);}
                else if(model.getUserType().equals("nation")){model.setRoleId(2L);}
                else if(model.getUserType().equals("province")){model.setRoleId(3L);}
                else if(model.getUserType().equals("city")){model.setRoleId(4L);}
                else if(model.getUserType().equals("district")){model.setRoleId(5L);}
                else if(model.getUserType().equals("school")){model.setRoleId(6L);}
                else if(model.getUserType().equals("teacher")){model.setRoleId(7L);}
                model.setUseStatus("normal");
                if(model.getUserId()==null){
                    TbSysUser sysUser=mapper.getUserByName(model.getUserName());
                    if(sysUser!=null){
                        msg="账号名称已存在";
                        result.setMsg(msg);
                        result.setCode(code);
                        return result;
                    }
                    sysUser=mapper.getUserByMobile(model.getMobile());
                    if(sysUser!=null){
                        msg="手机号码已存在";
                        result.setMsg(msg);
                        result.setCode(code);
                        return result;
                    }
                    model.setCreateTime(new Date());
                    model.setCreateAdminId(loginUser.getUserId());
                    add(model);
                }else{
                    model.setUpdateTime(new Date());
                    model.setUpdateAdminId(loginUser.getUserId());
                    model.setCreateTime(new Date());
                    model.setCreateAdminId(loginUser.getUserId());
                    update(model);
                }
                code=0;
                msg="保存成功";
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        result.setMsg(msg);
        result.setCode(code);
        return result;
    }

    @Override
    public AdminV1Result batchAdd(HttpServletRequest request) {
        HttpSession session = request.getSession();
        AdminV1Result result=new AdminV1Result<>();
        Integer code=1;
        String msg="保存失败";
        try {
            List<Map<String,Object>> dataList= (List<Map<String, Object>>) session.getAttribute(CommonContant.ADMIN_BATCH_SYS_USER_SESSION);
            log.info(JSON.toJSONString(dataList));
            if(dataList.size()==0){
                msg="请重新导入数据！";
                result.setMsg(msg);
                result.setCode(code);
                return result;
            }
            code=0;
            msg="保存成功";
        }catch (Exception e){
            e.printStackTrace();
        }
        result.setMsg(msg);
        result.setCode(code);
        return result;
    }

    @Override
    public boolean updatePwd(Long userId, String password, String newPassword) {
        boolean result=false;
        try
        {
            TbSysUser sysUser=mapper.selectByPrimaryKey(userId);
            if(sysUser!=null && sysUser.getPassword().equals(password) && CommonUtils.isNotBlank(newPassword))
            {
                sysUser.setPassword(newPassword);
                mapper.updateByPrimaryKey(sysUser);
                result=true;
            }
        }catch (Exception e){

        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized AdminV1Result importData(MultipartFile file, Map<String, Object> paramsMap, HttpServletRequest request) {
        HttpSession session = request.getSession();
        AdminV1Result result=new AdminV1Result<>();
        Map<String,Object> resultMap=new HashMap<>();
        List<Map<String,Object>> dataList=new ArrayList<>();
        Integer code=1;
        String msg="导入失败";
        try{
            String token= CommonUtils.parseStringData(paramsMap.get("token"));
            AdminLoginUserVO loginUser=this.getLoginUser(token);
            String ext = FileUtils.getExtend(file.getOriginalFilename());
            String today= DateUtils.format(new Date(),DateUtils.YMD);
            String temp="sysUser/"+today+"/";
            String originPath=basedir+temp;
            FileUtils.existOrmkdir(originPath);
            String fileName=DateUtils.format(new Date(),DateUtils.YMD_DASH_WITH_MITIME_STR);
            String detailDestination=originPath+fileName+"."+ext;
            File detailFile = new File(detailDestination);
            if (!detailFile.getParentFile().exists()) {
                detailFile.getParentFile().mkdirs();
            }
            try {
                file.transferTo(detailFile);
            } catch (Exception e) {
                if(detailFile.exists()){
                    detailFile.delete();
                }
            }
            if(detailFile!=null){
                ExcelReader reader = ExcelUtil.getReader(detailFile);
                int startRowIndex=2;
                List<List<Object>> readAll = reader.read(startRowIndex);
                if(readAll.size()>0){
                    int rowSize=5;
                    int idex=1;
                    for(List<Object> list:readAll){
                        Map<String,Object> mapObject=new LinkedHashMap<>();
                        int rowIndex=0;
                        mapObject.put("rowIndex0",idex);
                        String errMsg="√";
                        while (rowIndex<rowSize)
                        {
                            String rowValue=CommonUtils.parseStringData(list.get(rowIndex));
                            mapObject.put("rowIndex"+(rowIndex+1),rowValue);
//                            if(idex==8){
//                                errMsg="第"+idex+"行，账号重复！";
//                            }
                            rowIndex++;
                        }
                        mapObject.put("errMsg",errMsg);
                        dataList.add(mapObject);
                        idex++;

                    }
                    code=0;
                    msg="导入成功";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        session.setAttribute(CommonContant.ADMIN_BATCH_SYS_USER_SESSION, dataList);
        result.setMsg(msg);
        result.setCode(code);
        result.setCount(dataList.size());
        result.setData(dataList);
        return result;
    }


    @Override
    public String exportData(TbSysUser model) throws Exception {
        String url="";
        try {
            String path = request.getContextPath();
            List<TbSysUser> list=selectListBySQL(model);
            String timeStr= DateUtils.format(new Date(), DateUtils.YMD);
            String filePath= basedir+"/exportSysUser/"+timeStr+"/";
            FileUtils.existOrmkdir(filePath);
            String fileName="sysUser_"+DateUtils.format(new Date(),DateUtils.YMD_DASH_WITH_TIME_STR)+".xlsx";
            filePath=filePath+fileName;

            List<Map<String, Object>> rows = new ArrayList<>();
            if(list.size()>0)
            {
                int index=1;
                for(TbSysUser item:list){
                    Map<String, Object> row = new LinkedHashMap<>();
                    //序号
                    row.put("序号", index);
                    rows.add(row);
                    index++;
                }
            }
            // 通过工具类创建writer，默认创建xls格式
            ExcelWriter writer = ExcelUtil.getWriter(filePath);
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(rows, true);
            Font font = writer.createFont();
            font.setFontHeightInPoints((short) 12); //字体高度
            font.setFontName("微软雅黑");
            writer.getStyleSet().setFont(font, false);
            StyleSet styleSet = writer.getStyleSet();
            styleSet.setAlign(HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
            writer.setStyleSet(styleSet);
            Sheet sheet = writer.getSheet();
            for (int i = 0; i < 100; i++) {
                sheet.autoSizeColumn(i);
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            writer.flush(out, true);
            url="/admin/v1/common/downloadExcel?filePath=/exportSysUser/"+timeStr+"/"+fileName;
            // 关闭writer，释放内存
            writer.close();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        log.info("exportData...");
        return url;
    }
}
